package com.youhome.wechat.controller;

import com.youhome.common.config.OSSConfig;
import com.youhome.common.exception.CustomException;
import com.youhome.common.response.Result;
import com.youhome.common.response.ResultCode;
import com.youhome.service.model.BClient;
import com.youhome.service.model.BUser;
import com.youhome.service.service.*;
import com.youhome.utils.DateUtils;
import com.youhome.utils.TokenUtils;
import com.youhome.utils.ValidationUtils;
import com.youhome.wechat.dto.DTOClientUpdate;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * Created by chen365 on 2018/12/11.
 */
@RestController
@RequestMapping(value = "/user")
@Api(tags = "用户")
@Slf4j
public class UserController {
    @Autowired
    private TokenService tokenService;
    @Autowired
    private BUserService userService;
    @Autowired
    private BClientService clientService;
    @Autowired
    private JSMSValidateService jsmsValidateService;

    @ApiOperation(value = "获取用户信息", notes = "获取用户信息", response = BClient.class, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @GetMapping(value = "/info")
    public Object info(HttpServletRequest request) throws CustomException {

        String openid = tokenService.getOpenid(request);
        BUser currentUser = userService.getCurrentUser(openid);
        return new Result<>(ResultCode.SUCCESS, clientService.selectByUserId(currentUser.getUserId()));

        /*
        String authorization = request.getHeader("Authorization");
        if (StringUtils.isEmpty(authorization)) {
            return new Result<>(ResultCode.REQUIRE_AUTHORIZATION);
        }
        if (!authorization.startsWith("Bearer ")) {
            return new Result<>(ResultCode.FORMAT_ACCESS_TOKEN);
        }
        String token = authorization.substring("Bearer ".length());
        if (StringUtils.isEmpty(token)) {
            return new Result<>(ResultCode.REQUIRE_ACCESS_TOKEN);
        }
        //判断token 的有效期
        if (!TokenUtils.isExpired(token)) {
            return new Result<>(ResultCode.EXPIRE_ACCESS_TOKEN);
        }
        //判断token在redis里是否存在
        if (!tokenService.checkTokenByWX(token)) {
            return new Result<>(ResultCode.INVALID_ACCESS_TOKEN);
        }
        String openid = TokenUtils.getOpenIdByToken(token);
        if (StringUtils.isEmpty(openid)) {
            return new Result<>(ResultCode.FORMAT_ACCESS_TOKEN);
        }

        BUser currentUser = userService.getCurrentUser(openid);
        BClient client = clientService.selectByUserId(currentUser.getUserId());
        if (client == null) {
            return new Result<>(ResultCode.NOT_FILLED_CLIENT_INFO);
        }
        return new Result<>(ResultCode.SUCCESS, client);

        */
    }

    @ApiOperation(value = "修改用户信息", notes = "修改用户信息", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @PostMapping(value = "/update")
    public Object update(HttpServletRequest request, @ApiParam @Validated DTOClientUpdate dtoClientUpdate) throws CustomException {
        log.info("dtoClientUpdate==>>"+dtoClientUpdate.toString());
        ModelMapper modelMapper = new ModelMapper();
        clientService.updateOfWXUpdate(request, modelMapper.map(dtoClientUpdate, BClient.class));
        return new Result<>(ResultCode.SUCCESS);

        /*
        if (StringUtils.isEmpty(name)) {
            return new Result<>(ResultCode.EMPTY_NAME);
        }
        String authorization = request.getHeader("Authorization");
        if (StringUtils.isEmpty(authorization)) {
            return new Result<>(ResultCode.REQUIRE_AUTHORIZATION);
        }
        if (!authorization.startsWith("Bearer ")) {
            return new Result<>(ResultCode.FORMAT_ACCESS_TOKEN);
        }
        String token = authorization.substring("Bearer ".length());
        if (StringUtils.isEmpty(token)) {
            return new Result<>(ResultCode.REQUIRE_ACCESS_TOKEN);
        }
        //判断token 的有效期
        if (!TokenUtils.isExpired(token)) {
            return new Result<>(ResultCode.EXPIRE_ACCESS_TOKEN);
        }
        //判断token在redis里是否存在
        if (!tokenService.checkTokenByWX(token)) {
            return new Result<>(ResultCode.INVALID_ACCESS_TOKEN);
        }
        String openid = TokenUtils.getOpenIdByToken(token);
        if (StringUtils.isEmpty(openid)) {
            return new Result<>(ResultCode.FORMAT_ACCESS_TOKEN);
        }
        BUser user = userService.getCurrentUser(openid);
        //判断手机号是否已经注册
        if (user == null) {
            return new Result<>(ResultCode.UNBOUND_PHONE);
        }
        BClient entity = clientService.selectByUserId(user.getUserId());

        BClient client = new BClient();
        if (entity != null) {
            client.setClientId(entity.getClientId());
        } else {
            client.setUserId(user.getUserId());
            client.setPhone(user.getPhone());
        }

        client.setName(name);
        client.setEmail(email);
        client.setWeixin(weChat);
        client.setQq(qq);
        client.setInvestmentObjective(investmentObjective);
        client.setCapitalSource(capitalSource);
        client.setTendencyRoom(tendencyRoom);
        client.setTendencySite(tendencySite);
        client.setTendencyPrice(tendencyPrice);
        client.setTendencySize(tendencySize);
        client.setTendencySchool(tendencySchool);
        client.setProvince(province);
        client.setCity(city);
        client.setArea(area);
        client.setAddress(address);

        if (!StringUtils.isEmpty(birthDate)) {
            Date date = DateUtils.StrToDate(birthDate, "yyyy-MM-dd");
            client.setBirthdate(date);
        }

        client.setMarital(marital);
        client.setIncome(income);
        client.setJobTitle(jobTitle);
        client.setJobType(jobType);
        client.setSex(gender);

        if (clientService.save(client) > 0) {
            return new Result<>(ResultCode.SUCCESS);
        } else {
            return new Result<>(ResultCode.FAIL);
        }

        */
    }

    @ApiOperation(value = "绑定手机号", notes = "绑定手机号", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "phone", value = "手机号", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "msgId", value = "短信ID", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "msgCode", value = "短信验证码", required = true, paramType = "query")
    })
    @PostMapping(value = "/binding-phone")
    public Object bindingPhone(HttpServletRequest request, String phone, String msgId, String msgCode) throws CustomException {
        if (StringUtils.isEmpty(phone)) {
            return new Result<>(ResultCode.EMPTY_PHONE);
        }
        if (!ValidationUtils.isPhone(phone)) {
            return new Result<>(ResultCode.ERROR_PHONE);
        }

        if (StringUtils.isEmpty(msgId)) {
            return new Result<>(ResultCode.EMPTY_MSG_ID);
        }

        if (StringUtils.isEmpty(msgCode)) {
            return new Result<>(ResultCode.EMPTY_MSG_CODE);
        }

        if (!ValidationUtils.isNumeric(msgCode) || msgCode.length() != 6) {
            return new Result<>(ResultCode.FORMAT_MSG_CODE);
        }

        String authorization = request.getHeader("Authorization");
        if (StringUtils.isEmpty(authorization)) {
            return new Result<>(ResultCode.REQUIRE_AUTHORIZATION);
        }
        if (!authorization.startsWith("Bearer ")) {
            return new Result<>(ResultCode.FORMAT_ACCESS_TOKEN);
        }
        String token = authorization.substring("Bearer ".length());
        if (StringUtils.isEmpty(token)) {
            return new Result<>(ResultCode.REQUIRE_ACCESS_TOKEN);
        }
        //判断token 的有效期
        if (!TokenUtils.isExpired(token)) {
            return new Result<>(ResultCode.EXPIRE_ACCESS_TOKEN);
        }
        //判断token在redis里是否存在
        if (!tokenService.checkTokenByWX(token)) {
            return new Result<>(ResultCode.INVALID_ACCESS_TOKEN);
        }
        String openid = TokenUtils.getOpenIdByToken(token);
        if (StringUtils.isEmpty(openid)) {
            return new Result<>(ResultCode.FORMAT_ACCESS_TOKEN);
        }
        System.err.println("============================msgId:" + msgId + ", msgCode:" + msgCode + "==================================");

        boolean validate = jsmsValidateService.validate(phone, msgId, msgCode);
        if (!validate) {
            return new Result<>(ResultCode.VALIDATE_CODE_FAILED);
        }
        BUser user = userService.selectByPhone(phone);
        //判断手机号是否已经注册
        if (user != null) {
            //手机号未与openid 绑定
            if (StringUtils.isEmpty(user.getOpenid())) {
                BUser entity = new BUser();
                entity.setUserId(user.getUserId());
                entity.setOpenid(openid);
                int success = userService.updateByPrimaryKeySelective(entity);
                if (success > 0) {
                    return new Result<>(ResultCode.SUCCESS);
                } else {
                    return new Result<>(ResultCode.PHONE_BINDING_FAILED);
                }
            } else {
                return new Result<>(ResultCode.IS_BINDING_PHONE);
            }
        } else {
            //注册手机号
            user = new BUser();
            user.setPhone(phone);
            user.setOpenid(openid);
            user.setCtime(new Date());
            user.setReportCount(0);
            user.setEnabled(true);

            BUser bUser = userService.create(user);
            if (bUser == null) {
                return new Result<>(ResultCode.PHONE_BINDING_FAILED);
            } else {
                return new Result<>(ResultCode.SUCCESS);
            }
        }
    }


    @ApiOperation(value = "退出登陆", notes = "退出登陆", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @PostMapping(value = "/logout")
    public Object logout(HttpServletRequest request) {

        String authorization = request.getHeader("Authorization");
        if (StringUtils.isEmpty(authorization)) {
            return new Result<>(ResultCode.REQUIRE_AUTHORIZATION);
        }
        if (!authorization.startsWith("Bearer ")) {
            return new Result<>(ResultCode.FORMAT_ACCESS_TOKEN);
        }
        String token = authorization.substring("Bearer ".length());
        if (StringUtils.isEmpty(token)) {
            return new Result<>(ResultCode.REQUIRE_ACCESS_TOKEN);
        }
        //判断token 的有效期
        if (!TokenUtils.isExpired(token)) {
            return new Result<>(ResultCode.EXPIRE_ACCESS_TOKEN);
        }
        //判断token在redis里是否存在
        if (!tokenService.checkTokenByWX(token)) {
            return new Result<>(ResultCode.INVALID_ACCESS_TOKEN);
        }
        String openid = TokenUtils.getOpenIdByToken(token);
        if (StringUtils.isEmpty(openid)) {
            return new Result<>(ResultCode.FORMAT_ACCESS_TOKEN);
        }
        tokenService.cleanTokenByWX(token, openid);

        return new Result<>(ResultCode.SUCCESS);
    }
}
